﻿using Magicodes.WeiChat.Data;
using Magicodes.WeiChat.Data.Models.Site;
using Magicodes.WeChat.SDK;
using Magicodes.WeiChat.Infrastructure;
using Magicodes.WeiChat.Infrastructure.MvcExtension.Ajax;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.Media;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using Microsoft.AspNet.Identity;
using Magicodes.WeChat.SDK.Core.Apis.Material;
using Magicodes.WeChat.SDK.Apis.Material.Enums;

namespace Magicodes.WeiChat.Helpers.Resource
{
    public class SiteResourceHelper
    {
        /// <summary>
        /// 上传站点资源
        /// </summary>
        /// <param name="resoureType"></param>
        /// <param name="file"></param>
        /// <param name="db"></param>
        /// <param name="uploadToWeChatMaterial">是否以素材上传，否则走独立的上传接口（目前仅支持图片）</param>
        /// <returns></returns>
        public static Site_FileBase Upload(Site_ResourceType resoureType, string fileName, byte[] fileStream, AppDbContext db, out AjaxResponse ajaxMessage, bool uploadToWeChatMaterial = true)
        {
            ajaxMessage = new AjaxResponse() { Success = true };
            var fileSaveName = Guid.NewGuid().ToString("N") + Path.GetExtension(fileName);
            var tenantId = WeiChatApplicationContext.Current.TenantId;

            var dirName = tenantId.ToString();
            var path = Path.Combine(HttpContext.Current.Server.MapPath("~/MediaFiles"), dirName);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            path = Path.Combine(path, fileSaveName);
            File.WriteAllBytes(path, fileStream);
            MaterialType type = MaterialType.video;
            switch (resoureType.ResourceType)
            {
                case SiteResourceTypes.Gallery:
                    type = MaterialType.image;
                    break;
                case SiteResourceTypes.Voice:
                    type = MaterialType.voice;
                    break;
                case SiteResourceTypes.Video:
                    type = MaterialType.video;
                    break;
                //case SiteResourceTypes.Article:
                //case SiteResourceTypes.News:
                default:
                    ajaxMessage.Success = false;
                    ajaxMessage.Message = "不支持上传此类型";
                    return null;
            }
            string mediaId = null;
            string url = null;
            if (uploadToWeChatMaterial)
            {
                var result = WeChatApisContext.Current.MaterialApi.UploadForeverMaterial(path, null, null, type);
                if (!result.IsSuccess())
                {
                    ajaxMessage.Success = false;
                    ajaxMessage.Message = result.GetFriendlyMessage();
                }
                else
                {
                    mediaId = result.MediaId;
                    url = result.Url;
                }
            }
            else
            {
                var result = WeChatApisContext.Current.MaterialApi.UploadImage(path);
                if (!result.IsSuccess())
                {
                    ajaxMessage.Success = false;
                    ajaxMessage.Message = result.GetFriendlyMessage();
                }
                else
                {
                    url = result.Url;
                }
            }
            if (url != null)
            {
                switch (resoureType.ResourceType)
                {
                    case SiteResourceTypes.Gallery:
                        {
                            var pic = new Site_Image()
                            {
                                IsFrontCover = false,
                                MediaId = mediaId,
                                Name = fileName,
                                SiteUrl = string.Format("/MediaFiles/{0}/{1}", dirName, fileSaveName),
                                Url = url,
                                ResourcesTypeId = resoureType.Id,
                                CreateBy = HttpContext.Current.User.Identity.GetUserId(),
                                CreateTime = DateTime.Now,
                                TenantId = tenantId
                            };
                            db.Site_Images.Add(pic);
                            db.SaveChanges();
                            return pic;
                        }
                        break;
                    case SiteResourceTypes.Voice:
                        {
                            var voice = new Site_Voice()
                            {
                                MediaId = mediaId,
                                Name = fileName,
                                SiteUrl = string.Format("/MediaFiles/{0}/{1}", dirName, fileSaveName),
                                Url = url,
                                ResourcesTypeId = resoureType.Id,
                                CreateBy = HttpContext.Current.User.Identity.GetUserId(),
                                CreateTime = DateTime.Now,
                                TenantId = tenantId
                            };
                            db.Site_Voices.Add(voice);
                            db.SaveChanges();
                            return voice;
                        }
                        break;
                    case SiteResourceTypes.Video:
                        {
                            var video = new Site_Video()
                            {
                                MediaId = mediaId,
                                Name = fileName,
                                SiteUrl = string.Format("/MediaFiles/{0}/{1}", dirName, fileSaveName),
                                Url = url,
                                ResourcesTypeId = resoureType.Id,
                                CreateBy = HttpContext.Current.User.Identity.GetUserId(),
                                CreateTime = DateTime.Now,
                                TenantId = tenantId
                            };
                            db.Site_Videos.Add(video);
                            db.SaveChanges();
                            return video;
                        }
                        break;
                    default:
                        ajaxMessage.Success = false;
                        ajaxMessage.Message = "不支持上传此类型";
                        break;
                }
            }
            return null;
        }
    }
}